package com.qf.shiroboot.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

@Slf4j
public class RedisWebSessionManager extends DefaultWebSessionManager {

    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        //1. 通过SessionKey获取sessionId
        Serializable sessionId = getSessionId(sessionKey);
        if (sessionId == null) {
            log.debug("Unable to resolve session ID from SessionKey [{}].  Returning null to indicate a " +
                    "session could not be found.", sessionKey);
            return null;
        }
        //2. 去request中查询session对象
        WebSessionKey webSessionKey = (WebSessionKey) sessionKey;
        ServletRequest req = webSessionKey.getServletRequest();
        Session s = (Session) req.getAttribute(sessionId + "");
        if(s != null){
            return s;
        }

        //3. 去Redis查询Session
        s = retrieveSessionFromDataSource(sessionId);
        if (s == null) {
            //session ID was provided, meaning one is expected to be found, but we couldn't find one:
            String msg = "Could not find session with ID [" + sessionId + "]";
            throw new UnknownSessionException(msg);
        }

        //4. 将查询到的Session放到request对象中
        req.setAttribute(sessionId + "",s);

        //5. 返回session
        return s;
    }
}
